/**
 * Created by xiteng on 2017/5/3.
 */
import React, {Component} from 'react';
import {
    Text,
    View,
    TouchableOpacity,
    Image,
    PixelRatio,
    ScrollView,
    Switch,
    TextInput,
    DeviceEventEmitter,
    StyleSheet,
    Button
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import Toast from 'react-native-easy-toast'
import ContactsWrapper from 'react-native-contacts-wrapper'
import Constant from '../Contant'
import {observable, action, computed, autorun,observe} from 'mobx'
import {observer} from 'mobx-react/native'
import {GradientButton} from '../component/Button'
import addressMgrStore from '../store/AddrMgrStore'
import RequestUtil from "../util/NetUtil";

// 收货人联系电话  选择联系人组件
const UserForm = ({contactChooser, userNameChange, phoneNumChange, userName = '', phoneNum = ''}) => {

    // 输入框
    const InputCell = ({textChange, value, placeholder = '', title = '', keyboardType = 'default'}) => {
        return <View style={[styles.row, styles.borderBottom, {
            paddingVertical: 10,
            paddingHorizontal: 15,
            alignItems: 'center',
            backgroundColor: '#fff'
        }]}>
            <Text>{title}:</Text>
            <View style={{paddingHorizontal: 10}}>
                <TextInput
                    onEndEditing={textChange}
                    defaultValue={value}
                    style={{height: 40, width: 140, fontSize: 14}}
                    placeholder={placeholder}
                    keyboardType={keyboardType}
                    underlineColorAndroid='transparent'/>
            </View>
        </View>
    }

    return <View style={styles.row}>
        <View style={{flex: 3}}>
            <InputCell
                title="收货人"
                placeholder="收货人"
                textChange={userNameChange}
                value={userName}/>
            <InputCell
                title="联系电话"
                placeholder="手机号"
                keyboardType="phone-pad"
                textChange={phoneNumChange}
                value={phoneNum}/>
        </View>
        <TouchableOpacity style={[styles.center, {flex: 1}]} onPress={contactChooser}>
            <Icon name="ios-contact" size={24}/>
            <Text>选联系人</Text>
        </TouchableOpacity>
    </View>
}


// 通用cell
const CommonCell = ({title, desc, onClick}) => {
    return <TouchableOpacity
        onPress={onClick}
        style={[{
            padding: 15,
            alignItems: 'center',
            flexDirection: 'row'
        }, styles.borderBottom]}>
        <View style={{flex: 2}}>
            <Text style={{fontSize: 14}}>{title}</Text>
        </View>
        <View style={{flex: 7, paddingLeft: 10}}>
            <Text numberOfLines={2} style={styles.content}>{desc}</Text>
        </View>
    </TouchableOpacity>
}

const LabelItem = observer(({name,selected,onPress,index})=>{
    return <TouchableOpacity
        onPress={()=>{
            onPress(index)
        }}
        style={[styles.label, styles.border]}>
        <Text style={{color:selected?Constant.BLUECOLOR : Constant.TEXT_COLOR_3}}>{name}</Text>
    </TouchableOpacity>
})

class CreateAddressModel {
    constructor(poi) {
        this.adCode = poi.adCode;
        this.appendAddress = poi.appendAddress;
        this.cityCode = poi.cityCode;
        this.cityName = poi.cityName.length == 0 ? poi.pName : poi.cityName;
        this.latitude = poi.latitude;
        this.longtitude = poi.longitude;
        this.mappingAddress = poi.mappingAddress;
        this.pCode = poi.pCode;
        this.pName = poi.pName;
    }
}

class AddressModel {
    constructor(name, phone, poi, addressTagId) {
        this.name = name;
        this.phone = phone;
        this.addressTagId = addressTagId;
        this.createAddressModel = new CreateAddressModel(poi);
    }
}



@observer
class Tag extends Component{

    @observable selectedIndex = -1 ;

    onItemPress = (index)=>{
        this.props.onChange(this.props.tagList[index]);
        this.selectedIndex = index ;
    }

    render(){
        return <View style={{
            backgroundColor: '#fff',
            height: 50,
            alignItems: 'center',
            flexDirection: 'row'
        }}>
            <View style={{paddingLeft: 10}}>
                <Text>标签:</Text>
            </View>
            {
                this.props.tagList.map((tag, index) => {
                    return <View style={{marginHorizontal: 10}} key={index}>
                        <LabelItem
                            index={index}
                            onPress={this.onItemPress}
                            name={tag.name}
                            selected={index == this.selectedIndex}/>
                    </View>
                })
            }
        </View>
    }
}

@observer
export default class AddOrEditAddress extends Component {

    @observable poi='';
    @observable receiverName = this.editAddress!=null?this.editAddress.name:'';
    @observable receiverPhoneNumber = this.editAddress!=null?this.editAddress.phoneNum:'';

    @observable tagList = [];

    @observable receiverDetailAddr = this.editAddress!=null?this.editAddress.address.appendingAddress:'';

    static navigationOptions = {
        title: '新增地址',
    };

    constructor(props) {
        super(props);
        this.state = {
            isDefault: false,
        };
        let params = this.props.navigation.state.params ;
        let {editAddress} = params;
        if(editAddress!=undefined){
            this.editAddress=editAddress;
        }
        this.currentTag = null ;
        addressMgrStore.mapAuto.setEdit(false);
    }

    // 创建地址
    createDeliveryAddress() {
        if (this.verifyAddress()) {
            let poi = addressMgrStore.mapAuto.edit?addressMgrStore.mapAuto.TempPoi:addressMgrStore.activeAddress;
            poi.appendAddress = this.receiverDetailAddr;
            let tagId = this.currentTag ? this.currentTag.id : null ;
            let addM = new AddressModel(this.receiverName, this.receiverPhoneNumber, poi,tagId);
            RequestUtil.requestData('delivery/create', {
                createAddressModel: addM
            }).then((resp) => {
                    addressMgrStore.refreshDeliveryList();
                    this.props.navigation.goBack();
            }).catch(err=>{
                    this.refs.toast.show(err);
                }
            )
        }
    }
    //更新地址
    updateDeliveryAddress(){
        if (this.verifyAddress()) {
            let isChangeDetailAddr=addressMgrStore.mapAuto.edit;//编辑地址是否更改区域
            let tempPoi = addressMgrStore.mapAuto.TempPoi;
            if(isChangeDetailAddr){
                tempPoi.appendAddress = this.receiverDetailAddr;
            }
            let tagId = this.currentTag ? this.currentTag.id : null ;
            let updateParam={
                createAddressModel:{
                    addressTagId:tagId,
                    createAddressModel:{
                        adCode:isChangeDetailAddr?tempPoi.adCode:'',
                        appendAddress:isChangeDetailAddr?tempPoi.appendAddress:this.receiverDetailAddr,
                        cityCode:isChangeDetailAddr?tempPoi.cityCode:'',
                        cityName:isChangeDetailAddr?tempPoi.cityName:this.editAddress.address.cityName,
                        latitude:isChangeDetailAddr?tempPoi.latitude:this.editAddress.position.latitude,
                        longtitude:isChangeDetailAddr?tempPoi.longitude:this.editAddress.position.longitude,
                        mappingAddress:isChangeDetailAddr?tempPoi.mappingAddress:this.editAddress.address.mapAddress,
                        pCode:isChangeDetailAddr?tempPoi.pCode:'',
                        pName:isChangeDetailAddr?tempPoi.pName:'',
                    },
                    name:this.receiverName,
                    phone:this.receiverPhoneNumber,
                },
                id:this.editAddress.id
            };
            RequestUtil.requestData('delivery/update', updateParam).then((resp) => {
                    addressMgrStore.refreshDeliveryList();
                    this.props.navigation.goBack(null);
            }).catch(err=>{
                    this.refs.toast.show(err);
                }
            )
        }
    }

    // 验证地址
    verifyAddress() {
        let verifyOK = true;
        if (this.receiverName.length == 0) {
            verifyOK = false;
            this.refs.toast.show('请输入收货人名称！');
            return;
        }
        if (this.receiverPhoneNumber.length == 0) {
            verifyOK = false;
            this.refs.toast.show('请输入联系电话！');
            return;
        }
        if (this.receiverDetailAddr.length == 0) {
            verifyOK = false;
            this.refs.toast.show('请输入详细地址信息');
            return;
        }
        return verifyOK;
    }


    componentDidMount() {
        // 获取标签列表
        RequestUtil.requestData('/delivery/tagList', {}).then((resp) => {
            if (resp instanceof Array) {
                this.tagList = resp;
            }
        })
    }
    @observer
    getMappingPosition(){
        let position={
            latitude:'',
            longitude:''
        };
        if(this.editAddress!=null) {
            if(addressMgrStore.mapAuto.edit){
                position.latitude=addressMgrStore.mapAuto.TempPoi.latitude;
                position.longitude=addressMgrStore.mapAuto.TempPoi.longitude;
            }else {
                position.latitude=this.editAddress.position.latitude;
                position.longitude=this.editAddress.position.longitude;
            }
        }else {
            position.latitude=addressMgrStore.activeAddress.latitude;
            position.longitude=addressMgrStore.activeAddress.longitude;
        }
        return position;
    }
    @observer
    getMappingAddress(){
        if(this.editAddress!=null){
            return addressMgrStore.mapAuto.edit?addressMgrStore.mapAuto.TempPoi.mappingAddress:this.editAddress.address.mapAddress;
        }else {
            return addressMgrStore.mapAuto.edit?addressMgrStore.mapAuto.TempPoi.mappingAddress:addressMgrStore.activeAddress.mappingAddress;
        }
    }
    render() {
        return <View style={{flex: 1, backgroundColor: Constant.GRAYBGCOLOR}}>
            <ScrollView>
                <UserForm
                    contactChooser={() => {
                        ContactsWrapper.getContact()
                            .then((contact) => {
                                this.receiverName = contact.name;
                                this.receiverPhoneNumber = contact.phone;

                            })
                            .catch((error) => {
                                console.log("ERROR CODE: ", error.code);
                                console.log("ERROR MESSAGE: ", error.message);
                            })
                    }}
                    userName={this.receiverName}
                    phoneNum={this.receiverPhoneNumber}
                    userNameChange={(event) => {
                        let text = event.nativeEvent.text
                        this.receiverName = text;
                    }}
                    phoneNumChange={(event) => {
                        let text = event.nativeEvent.text
                        this.receiverPhoneNumber = text;
                    }}
                />
                <View>
                    <View style={{backgroundColor: '#fff'}}>
                        <View style={{backgroundColor: '#fff'}}>
                            <View style={{backgroundColor: '#fff', paddingVertical: 5}}>
                                <CommonCell
                                    onClick={() => {
                                        this.props.navigation.navigate('Map',{position:this.getMappingPosition()});
                                    }}
                                    title="所在区域:"
                                    desc={this.getMappingAddress()}/>
                            </View>
                            <View style={[{
                                height: 60,
                                backgroundColor: '#fff'
                            }, styles.borderBottom]}>
                                <View>
                                    <TextInput
                                        onChangeText={(text) => {
                                            this.receiverDetailAddr = text
                                        }}
                                        numberOfLines={4}
                                        multiline={true}
                                        style={[{
                                            position: 'absolute',
                                            left: 10,
                                            right: 20,
                                            height: 60,
                                            fontSize: 14
                                        }, styles.borderBottom]}
                                        value={this.receiverDetailAddr}
                                        placeholder={'请填写详细地址'}/>
                                </View>
                            </View>
                            <Tag
                                onChange={(tag)=>{
                                    this.currentTag = tag ;
                                }}
                                tagList={this.tagList}/>
                        </View>
                    </View>
                </View>
                <View style={{marginBottom: 20, marginTop: 20, height: 40, paddingHorizontal: 15}}>
                    <GradientButton
                        title="保存"
                        onPress={this.editAddress==null?this.createDeliveryAddress.bind(this):this.updateDeliveryAddress.bind(this)}/>
                </View>
            </ScrollView>
            <Toast ref="toast" position='center'/>
        </View>
    }

}

const styles = {
    borderBottom: {
        borderBottomColor: Constant.SEPLINECOLOR,
        borderBottomWidth: StyleSheet.hairlineWidth
    },
    label: {
        paddingVertical: 5,
        paddingHorizontal: 10
    },
    border: {
        borderColor: Constant.SEPLINECOLOR,
        borderWidth: 1 / PixelRatio.get()
    },
    contactContainer: {
        borderLeftWidth: 1 / PixelRatio.get(),
        borderLeftColor: Constant.SEPLINECOLOR,
        justifyContent: 'center'
    },
    center: {
        alignItems: 'center',
        backgroundColor: Constant.GRAYBGCOLOR,
        justifyContent: 'center'
    },
    content: {
        fontSize: 14,
        fontWeight: '300',
    },
    row: {
        flexDirection: 'row'
    }

}